package com.jxl.springboot.game.service;

import com.jxl.springboot.game.mapper.GameInfoMapper;
import com.jxl.springboot.game.pojo.GameInfo;
import com.jxl.springboot.game.pojo.Page;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 游戏信息业务
 *
 * @author 江雪林
 * @create 2021-03-29
 */
@Service
public class GameInfoService {
    @Resource
    private GameInfoMapper gameInfoMapper;

    private List<GameInfo> getAllPassedGame(Integer index, Integer size) {
        return gameInfoMapper.findAllPassedGame(index, size);
    }

    public Page<GameInfo> getPageOfPassedGame(Integer pageNo, Integer pageSize) {
        if (pageNo <= 0 || pageSize <= 0) {
            return null;
        }
        Page<GameInfo> page = new Page<GameInfo>();
        page.setPageTotalCount(gameInfoMapper.findCountPassedGame());
        page.setPageSize(pageSize);
        page.setPageTotal(page.getPageTotalCount() % page.getPageSize() == 0 ?
                page.getPageTotalCount() / page.getPageSize() : (page.getPageTotalCount() / page.getPageSize() + 1));
        page.setPageNo(pageNo);
        page.setItmes(this.getAllPassedGame((page.getPageNo() - 1) * pageSize, pageSize));
        return page;
    }

    private List<GameInfo> getGamesByUserId(Integer id, Integer index, Integer size) {
        return gameInfoMapper.findGameByUserId(id, index, size);
    }

    public Page<GameInfo> getPageGamesByUserId(Integer id, Integer pageNo, Integer pageSize) {
        if (pageNo <= 0 || pageSize <= 0 || id <= 0) {
            return null;
        }
        Page<GameInfo> page = new Page<GameInfo>();
        page.setPageTotalCount(gameInfoMapper.findCountByUserId(id));
        page.setPageSize(pageSize);
        page.setPageTotal(page.getPageTotalCount() % page.getPageSize() == 0 ?
                page.getPageTotalCount() / page.getPageSize() : (page.getPageTotalCount() / page.getPageSize() + 1));
        page.setPageNo(pageNo);
        page.setItmes(this.getGamesByUserId(id, (page.getPageNo() - 1) * pageSize, pageSize));
        return page;
    }

    public GameInfo getGameInfoById(Integer id) {
        if (id == null || id <= 0 || "".equals(id)) {
            return null;
        }
        return gameInfoMapper.findGameById(id);
    }

    public boolean udpateGame(GameInfo gameInfo) {
        if (gameInfo != null && gameInfo.getId() != null && gameInfo.getId() > 0) {
            GameInfo old = getGameInfoById(gameInfo.getId());
            if (old != null) {
                return gameInfoMapper.updateGameInfo(gameInfo) > 0;
            }
        }
        return false;
    }
}
